package array.sliding_window;

import java.util.HashMap;
import java.util.Map;

/**
 * 最小覆盖字串
 */
public class MinWindow {

    public String minWindow(String s, String t) {

        Map<Character, Integer> window = new HashMap<>();
        Map<Character, Integer> need = new HashMap<>();
        for (char c : t.toCharArray()) {
            need.put(c, need.getOrDefault(c, 0) + 1);
        }
        int left = 0, right = 0;
        int valid = 0;
        // 记录最小覆盖字串的起始索引及长度
        int start = 0, len = Integer.MAX_VALUE;
        while (right < s.length()) {
            // c 是将要移入窗口的字符
            char c = s.charAt(right);
            // 扩大窗口
            right++;
            // 进行窗口内一系列数据的更新
            if (need.containsKey(c)) {
                window.put(c, window.getOrDefault(c, 0) + 1);
                if (window.get(c).equals(need.get(c))) {
                    valid++;
                }
            }

            // 判断窗口是否需要收缩
            while (valid == need.size()) {
                // 在此更新最小子串
                if (right - left < len) {
                    start = left;
                    len = right - left;
                }
                // d 是将要移出窗口的字符
                char d = s.charAt(left);
                // 缩小窗口
                left++;

                if (need.containsKey(d)) {
                    if (window.get(d).equals(need.get(d)))
                        valid--;
                    window.put(d, window.getOrDefault(d, 0) - 1);
                }
            }
        }
        return len == Integer.MAX_VALUE ? "" : s.substring(start, start + len);
    }
}
